<template>
  <div class="products-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>产品管理</span>
          <div class="header-controls">
            <el-button type="primary" @click="handleAddProduct">添加产品</el-button>
          </div>
        </div>
      </template>

      <!-- 搜索栏 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="产品名称">
          <el-input v-model="searchForm.name" placeholder="请输入产品名称" />
        </el-form-item>
        <el-form-item label="类别">
          <el-select v-model="searchForm.category" placeholder="请选择类别" filterable>
            <el-option label="全部" value="" />
            <el-option label="新鲜水果" value="新鲜水果" />
            <el-option label="绿色蔬菜" value="绿色蔬菜" />
            <el-option label="优质肉类" value="优质肉类" />
            <el-option label="新鲜海鲜" value="新鲜海鲜" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table :data="filteredProducts" style="width: 100%">
        <el-table-column prop="name" label="产品名称" />
        <el-table-column prop="category" label="类别">
          <template #default="{ row }">
            <el-tag>{{ getCategoryText(row.category) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="unit" label="单位" />
        <el-table-column prop="costPrice" label="采购价格">
          <template #default="{ row }">
            ¥{{ row.costPrice.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column label="库存情况">
          <template #default="{ row }">
            <el-popover
              placement="right"
              :width="400"
              trigger="click"
            >
              <template #reference>
                <el-button type="primary" link @click="handleViewStock(row)">查看库存</el-button>
              </template>
              <div class="stock-info">
                <h4>各仓库库存情况</h4>
                <el-table :data="row.stockInfo" size="small">
                  <el-table-column prop="warehouse" label="仓库" />
                  <el-table-column prop="stock" label="当前库存" />
                  <el-table-column prop="minStock" label="最低库存" />
                  <el-table-column prop="status" label="状态">
                    <template #default="{ row }">
                      <el-tag :type="getStockStatusType(row.status)">
                        {{ row.status }}
                      </el-tag>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button type="success" size="small" @click="handleQuickPurchase(row)">快速采购</el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加/编辑产品对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑产品' : '添加产品'"
      width="500px"
    >
      <el-form
        ref="productFormRef"
        :model="productForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="产品名称" prop="name">
          <el-input v-model="productForm.name" />
        </el-form-item>
        <el-form-item label="类别" prop="category">
          <el-select v-model="productForm.category" placeholder="选择类别">
            <el-option v-for="option in categoryOptions" :key="option.value" :label="option.label" :value="option.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-input v-model="productForm.unit" />
        </el-form-item>
        <el-form-item label="采购价格" prop="costPrice">
          <el-input-number v-model="productForm.costPrice" :precision="2" :step="0.1" :min="0" />
        </el-form-item>
        <el-form-item label="最低库存" prop="minStock">
          <el-input-number v-model="productForm.minStock" :min="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 快速采购对话框 -->
    <el-dialog
      v-model="purchaseDialogVisible"
      title="快速采购"
      width="500px"
    >
      <el-form
        ref="purchaseFormRef"
        :model="purchaseForm"
        :rules="purchaseRules"
        label-width="100px"
      >
        <el-form-item label="采购数量" prop="quantity">
          <el-input-number 
            v-model="purchaseForm.quantity" 
            :min="1" 
            :step="10"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="目标仓库" prop="warehouse">
          <el-select
            v-model="purchaseForm.warehouse"
            placeholder="选择仓库"
            clearable
            style="width: 200px"
          >
            <el-option
              v-for="w in warehouses"
              :key="w.id"
              :label="w.name"
              :value="w.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="预计到货" prop="expectedDate">
          <el-date-picker
            v-model="purchaseForm.expectedDate"
            type="date"
            placeholder="选择日期"
            :disabled-date="disabledDate"
            value-format="YYYY-MM-DD"
            format="YYYY-MM-DD"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="purchaseForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="purchaseDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handlePurchaseSubmit">确认采购</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useProductStore } from '@/stores/productStore'
import axios from 'axios'
import { getToken } from '@/utils/auth'

// 配置 axios 默认值
axios.defaults.baseURL = 'http://localhost:8000'
axios.defaults.timeout = 15000
axios.defaults.withCredentials = true

// 搜索查询
const searchQuery = ref('')
const store = useProductStore()
const productFormRef = ref(null)

// 仓库列表
const warehouses = ref([])

// 获取仓库列表
const fetchWarehouses = async () => {
  try {
    const token = getToken()
    if (!token) {
      ElMessage.warning('请先登录')
      return
    }

    const response = await axios.get('/api/warehouses/', {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })

    // 处理不同的响应格式
    if (Array.isArray(response.data)) {
      warehouses.value = response.data
    } else if (response.data.results && Array.isArray(response.data.results)) {
      warehouses.value = response.data.results
    } else {
      warehouses.value = []
      console.warn('未获取到仓库数据:', response.data)
    }

    if (warehouses.value.length === 0) {
      ElMessage.warning('未找到任何仓库')
    }
  } catch (error) {
    console.error('获取仓库列表失败:', error)
    ElMessage.error('获取仓库列表失败')
    warehouses.value = []
  }
}

// 产品类别选项
const categoryOptions = ref([])

// 获取类别列表
const fetchCategories = async () => {
  try {
    const token = getToken()
    if (!token) {
      ElMessage.warning('请先登录')
      categoryOptions.value = []
      return
    }

    const response = await axios.get('/api/categories/', {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })
    
    if (Array.isArray(response.data)) {
      categoryOptions.value = response.data.map(category => ({
        label: category.description || category.name,
        value: category.id
      }))
    } else if (response.data.results && Array.isArray(response.data.results)) {
      categoryOptions.value = response.data.results.map(category => ({
        label: category.description || category.name,
        value: category.id
      }))
    } else {
      categoryOptions.value = []
      ElMessage.warning('未找到任何类别')
    }

    console.log('Final category options:', categoryOptions.value)
  } catch (error) {
    console.error('获取类别列表失败:', error)
    ElMessage.error('获取类别列表失败')
    categoryOptions.value = []
  }
}

// 获取类别显示文本
const getCategoryText = (category) => {
  if (!category) return '未知'
  
  // 如果是对象且有 category_detail
  if (typeof category === 'object') {
    if (category.category_detail?.description) {
      return category.category_detail.description
    }
    if (category.description) {
      return category.description
    }
    if (category.name) {
      // 根据名称返回完整描述
      switch(category.name.toLowerCase()) {
        case '水果':
          return '新鲜水果'
        case '蔬菜':
          return '绿色蔬菜'
        case '肉类':
          return '优质肉类'
        case '海鲜':
          return '新鲜海鲜'
        default:
          return category.name
      }
    }
  }

  // 如果是字符串，进行转换
  if (typeof category === 'string') {
    switch(category.toLowerCase()) {
      case '水果':
        return '新鲜水果'
      case '蔬菜':
        return '绿色蔬菜'
      case '肉类':
        return '优质肉类'
      case '海鲜':
        return '新鲜海鲜'
      default:
        return category
    }
  }

  // 如果是ID，从选项中查找
  const option = categoryOptions.value.find(opt => opt.value === category)
  if (option) return option.label

  return '未知'
}

// 获取产品列表
const fetchProducts = async () => {
  try {
    const token = getToken()
    if (!token) {
      ElMessage.warning('请先登录')
      return
    }

    const response = await axios.get('/api/products/', {
      params: {
        page: 1,
        limit: 50,
        include_category_details: true  // 请求包含类别详细信息
      },
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })

    let productsData = []
    if (response.data?.results) {
      productsData = response.data.results
    } else if (Array.isArray(response.data)) {
      productsData = response.data
    }

    // 处理每个商品的数据
    const processedProducts = await Promise.all(productsData.map(async product => {
      // 获取库存信息
      const stockInfo = await fetchStockInfo(product.id)
      
      // 获取类别详细信息
      let categoryInfo = product.category
      if (typeof product.category === 'number' || typeof product.category === 'string') {
        try {
          const categoryResponse = await axios.get(`/api/categories/${product.category}/`, {
            headers: {
              'Authorization': `Bearer ${token}`
            }
          })
          categoryInfo = categoryResponse.data
        } catch (error) {
          console.error('获取类别详情失败:', error)
        }
      }

      return {
        ...product,
        price: Number(product.price) || 0,
        costPrice: Number(product.cost_price) || 0,
        minStock: Number(product.min_stock) || 0,
        category: categoryInfo,
        stockInfo: stockInfo.map(item => ({
          warehouse: item.warehouse_name || '未知仓库',
          stock: Number(item.current_stock || 0),
          minStock: Number(item.min_stock || 0),
          status: item.status === 'normal' ? '正常' : 
                 item.status === 'warning' ? '低库存' : 
                 item.status === 'overflow' ? '超量' : 
                 item.status === 'expired' ? '过期' : '未知'
        }))
      }
    }))

    store.setProducts(processedProducts)
  } catch (error) {
    console.error('获取产品列表失败:', error)
    ElMessage.error('获取产品列表失败')
    store.setProducts([])
  }
}

// 获取库存信息
const fetchStockInfo = async (productId) => {
  try {
    const token = getToken()
    if (!token) {
      ElMessage.warning('请先登录')
      return []
    }

    // 先获取产品信息以获取产品名称
    const productResponse = await axios.get(`/api/products/${productId}/`, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })

    const productName = productResponse.data.name
    console.log('Product name:', productName)

    // 使用产品名称查询库存
    const response = await axios.get('/api/inventory/', {
      params: { product_name: productName },
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })

    console.log('Inventory response:', response.data)
    
    // 如果响应中没有 results 字段，尝试使用整个响应数据
    let inventoryData = response.data.results || response.data || []
    
    // 确保 inventoryData 是数组
    if (!Array.isArray(inventoryData)) {
      inventoryData = [inventoryData]
    }
    
    console.log('Processed inventory data:', inventoryData)
    
    // 如果没有库存数据，为每个仓库创建一个默认的库存记录
    if (inventoryData.length === 0 && warehouses.value.length > 0) {
      inventoryData = warehouses.value.map(warehouse => ({
        warehouse_name: warehouse.name,
        current_stock: 0,
        min_stock: 0,
        max_stock: null,
        status: 'out_of_stock'
      }))
    }

    return inventoryData
  } catch (error) {
    console.error('获取库存信息失败:', error)
    return []
  }
}

// 获取库存状态文本
const getStockStatusText = (status) => {
  const textMap = {
    normal: '正常',
    warning: '低库存',
    overflow: '超量',
    expired: '过期',
    out_of_stock: '无库存'
  }
  return textMap[status] || '未知'
}

// 根据库存数量计算库存状态
const getCalculatedStockStatus = (item) => {
  const stock = Number(item.current_stock || 0)
  const minStock = Number(item.min_stock || 10)
  const maxStock = Number(item.max_stock)
  
  if (stock <= 0) return 'out_of_stock'
  if (stock <= minStock) return 'warning'
  if (maxStock && stock > maxStock) return 'overflow'
  return 'normal'
}

// 获取库存状态样式
const getStockStatusType = (status) => {
  const typeMap = {
    normal: 'success',
    warning: 'warning',
    overflow: 'danger',
    expired: 'danger',
    out_of_stock: 'danger'
  }
  return typeMap[status] || 'info'
}

// 搜索表单
const searchForm = ref({
  name: '',
  category: ''
})

// 搜索和重置
const handleSearch = () => {
  filterProducts()
}

const handleReset = () => {
  searchForm.value = {
    name: '',
    category: ''
  }
  filterProducts()
}

// 前端全量过滤函数
const filterProducts = () => {
  let filtered = store.products

  // 名称搜索
  if (searchForm.value.name) {
    const nameQuery = searchForm.value.name.toLowerCase().trim()
    filtered = filtered.filter(p => 
      (p.name || '').toLowerCase().includes(nameQuery)
    )
  }

  // 类别搜索
  if (searchForm.value.category) {
    const categoryQuery = searchForm.value.category
    filtered = filtered.filter(p => {
      const categoryText = getCategoryText(p.category)
      return categoryText.includes(categoryQuery)
    })
  }

  return filtered
}

// 修改过滤后的产品列表计算属性
const filteredProducts = computed(() => filterProducts())

// 添加/编辑对话框
const dialogVisible = ref(false)
const isEdit = ref(false)
const productForm = ref({
  id: null,
  name: '',
  category: '',
  unit: '',
  costPrice: 0,
  minStock: 0,
  stockInfo: [],
  supplier: null
})

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入产品名称', trigger: 'blur' }],
  category: [{ required: true, message: '请选择类别', trigger: 'change' }],
  unit: [{ required: true, message: '请输入单位', trigger: 'blur' }],
  costPrice: [{ required: true, message: '请输入采购价格', trigger: 'blur' }],
  minStock: [{ required: true, message: '请输入最低库存', trigger: 'blur' }]
}

// 处理添加产品
const handleAddProduct = () => {
  isEdit.value = false
  productForm.value = {
    id: null,
    name: '',
    category: '',
    unit: '',
    costPrice: 0,
    minStock: 0,
    stockInfo: warehouses.value.map(w => ({
      warehouse: w.name,
      currentStock: 0,
      minStock: 0,
      status: '正常'
    })),
    supplier: null
  }
  dialogVisible.value = true
}

// 处理编辑产品
const handleEdit = (row) => {
  isEdit.value = true
  console.log('Editing product:', row)  
  
  let categoryId
  if (typeof row.category === 'object') {
    categoryId = row.category.id
  } else if (typeof row.category === 'number') {
    categoryId = row.category
  } else if (row.category_detail) {
    categoryId = row.category_detail.id
  } else {
    console.warn('无法获取类别ID:', row.category)
    categoryId = null
  }

  productForm.value = {
    id: row.id,
    name: row.name,
    category: categoryId,
    unit: row.unit,
    costPrice: Number(row.cost_price || 0),
    minStock: Number(row.min_stock || 0),
    stockInfo: row.stockInfo || [],
    supplier: row.supplier
  }
  
  dialogVisible.value = true
}

// 处理删除产品
const handleDelete = async (row) => {
  try {
    const token = getToken()
    if (!token) {
      ElMessage.warning('请先登录')
      return
    }

    await ElMessageBox.confirm(`确认删除产品 "${row.name}" 吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await axios.delete(`/api/products/${row.id}/`, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })

    ElMessage.success('产品删除成功')
    await fetchProducts()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除产品失败')
    }
  }
}

// 提交保存
const handleSubmit = async () => {
  try {
    const token = getToken()
    if (!token) {
      ElMessage.warning('请先登录')
      return
    }

    await productFormRef.value.validate()

    let supplierId
    if (isEdit.value) {
      supplierId = productForm.value.supplier
    } else {
      supplierId = 1
    }

    // 确保类别ID是数字类型
    const categoryId = Number(productForm.value.category)
    if (isNaN(categoryId)) {
      ElMessage.error('无效的类别ID')
      return
    }

    const productData = {
      name: productForm.value.name,
      category: categoryId,
      unit: productForm.value.unit,
      cost_price: Number(productForm.value.costPrice),
      min_stock: Number(productForm.value.minStock),
      supplier: supplierId,
      price: Number((Number(productForm.value.costPrice) * 1.2).toFixed(2)),  // 保留两位小数
      status: 'active'
    }

    // 验证价格长度
    if (String(productData.price).replace('.', '').length > 10) {
      ElMessage.error('价格不能超过10位数字')
      return
    }

    console.log('Submitting product data:', productData)

    if (isEdit.value) {
      await axios.put(`/api/products/${productForm.value.id}/`, productData, {
        headers: {
          'Authorization': `Bearer ${token}`
        }
      })
      ElMessage.success('产品更新成功')
    } else {
      await axios.post('/api/products/', productData, {
        headers: {
          'Authorization': `Bearer ${token}`
        }
      })
      ElMessage.success('产品创建成功')
    }

    dialogVisible.value = false
    await fetchProducts()
  } catch (error) {
    console.error('保存产品失败:', error)
    if (error.response?.data) {
      console.error('错误详情:', error.response.data)
      const errorMessage = Object.entries(error.response.data)
        .map(([key, value]) => `${key}: ${value}`)
        .join('\n')
      ElMessage.error(errorMessage || '保存产品失败')
    } else {
      ElMessage.error('保存产品失败')
    }
  }
}

// 处理查看库存
const handleViewStock = async (row) => {
  try {
    const stockInfo = await fetchStockInfo(row.id)
    row.stockInfo = stockInfo.map(item => ({
      warehouse: item.warehouse_name || '未知仓库',
      stock: Number(item.current_stock || 0),
      minStock: Number(item.min_stock || 0),
      status: item.status === 'normal' ? '正常' : 
             item.status === 'warning' ? '低库存' : 
             item.status === 'overflow' ? '超量' : 
             item.status === 'expired' ? '过期' : '未知'
    }))
  } catch (error) {
    ElMessage.error('获取库存信息失败')
  }
}

// 快速采购
const purchaseDialogVisible = ref(false)
const currentProduct = ref(null)
const purchaseForm = ref({
  quantity: 1,
  warehouse: null,
  expectedDate: null,
  remark: ''
})

const purchaseRules = {
  quantity: [{ required: true, message: '请输入采购数量', trigger: 'blur' }],
  warehouse: [{ required: true, message: '请选择目标仓库', trigger: 'change' }],
  expectedDate: [{ required: true, message: '请选择预计到货日期', trigger: 'change' }]
}

// 处理快速采购
const handleQuickPurchase = async (row) => {
  currentProduct.value = row
  purchaseForm.value = {
    quantity: 1,
    warehouse: null,
    expectedDate: null,
    remark: ''
  }
  // 确保获取最新的仓库列表
  await fetchWarehouses()
  purchaseDialogVisible.value = true
}

// 禁用过去的日期
const disabledDate = (time) => {
  return time.getTime() < Date.now() - 8.64e7
}

// 提交采购
const handlePurchaseSubmit = async () => {
  try {
    const token = getToken()
    if (!token) {
      ElMessage.warning('请先登录')
      return
    }

    // 表单验证
    if (!purchaseForm.value.quantity || !purchaseForm.value.warehouse || !purchaseForm.value.expectedDate) {
      ElMessage.warning('请填写完整的采购信息')
      return
    }

    const orderData = {
      supplier: currentProduct.value.supplier || 1, // 使用产品的供应商或默认供应商
      order_date: new Date().toISOString().split('T')[0],
      expected_delivery_date: purchaseForm.value.expectedDate,
      status: 'pending',
      remark: purchaseForm.value.remark || '',
      items: [{
        product: currentProduct.value.id,
        quantity: purchaseForm.value.quantity,
        unit_price: currentProduct.value.costPrice,
        warehouse: purchaseForm.value.warehouse
      }]
    }

    console.log('Submitting purchase order:', orderData)

    await axios.post('/api/purchase-orders/', orderData, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })

    ElMessage.success('采购订单创建成功')
    purchaseDialogVisible.value = false
    await fetchProducts()
  } catch (error) {
    console.error('创建采购订单失败:', error.response?.data || error)
    const errorMsg = error.response?.data?.detail || '创建采购订单失败'
    ElMessage.error(errorMsg)
  }
}

onMounted(async () => {
  try {
    await Promise.all([
      fetchCategories(),
      fetchWarehouses(),
      fetchProducts()
    ])
  } catch (error) {
    console.error('初始化数据失败:', error)
  }
})
</script>

<style scoped>
.products-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-controls {
  display: flex;
  align-items: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.stock-info {
  padding: 10px;
}

.stock-info h4 {
  margin-bottom: 15px;
  color: #303133;
}

.search-form {
  margin-bottom: 20px;
}
</style>